<?php
class common_region_zone_concept extends system_concept_abstract {
	
	public function init() {	
		$this->setModel('common_region_zone_model', 'zone');
		$this->setJoinLeftModel('common_region_city_model', 'city.id = zone.city_id', 'city');
		$this->setJoinLeftModel('common_region_model', 'province.id = city.province_id', 'province');
		$this->setModelCols('zone', array('id', 'name', 'ename', 'city_id', 'zipcode', 'areacode'));
		$this->setModelCols('city', array('name' => 'city_name', 'province_id'));
		$this->setModelCols('province', array('name' => 'province_name'));
	}

	public function save($row) {
		if($row->getName() == null) {
			throw new common_exception("Name can not be empty.");
		}
		if($row->getCityId() == null) {
			throw new common_exception("City can not be empty.");
		}
		if($row->getAreacode() == null) {
			throw new common_exception("Area Code can not be empty.");
		}
		if($row->getId()) {
			if($this->fetch(array('zone.id != ?' => $row->getId(), 'zone.city_id = ?' => $row->getProvinceId(), 'zone.name = ?' => $row->getName()))) {
				throw new common_exception("Name ({$row->getName()}) is already existing.");
			}
			$this->getModel('zone')->update($row->getModelData('zone'), array('id=?' => $row->getId()));
			return $row;
		}
		if($this->fetch(array('zone.city_id = ?' => $row->getProvinceId(), 'zone.name = ?' => $row->getName()))) {
			throw new common_exception("Name ({$row->getName()}) is already existing.");
		}
		$id = $this->getModel('zone')->insert($row->getModelData('zone'));
		$row->setId($id);
		return $row;
	}
	
	protected $_city = null;
	public function getCity($row) {
		if($this->_city === null || $this->_city->getId() != $row->getCityId()) {
			$concept = new common_region_city_concept();
			$this->_city = $concept->fetch(array('city.id = ?' => $row->getCityId()));
		}
		return $this->_city;
	}

}